package org.visionlibrary.image.filters.bluring;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class BasicBlur extends AbstractFilter {
	protected int xradius = 3;
	protected int yradius = 3;

	public BasicBlur() {
		this(3, 3);
	}

	public BasicBlur(int verticalradius, int horizontalradius) {
		this.yradius = verticalradius;
		this.xradius = horizontalradius;
	}

	public BasicBlur(int radius) {
		this.xradius = radius;
		this.yradius = radius;
	}

	public int getXRadius() {
		return xradius;
	}

	public void setXRadius(int radius) {
		this.xradius = radius;
	}

	public int getYRadius() {
		return yradius;
	}

	public void setYRadius(int radius) {
		this.xradius = radius;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);
		
		int maxX = src.getWidth();
		int maxY = src.getHeight();

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				for (int ch = 0; ch < src.getNumBands(); ch++) {
					int total = 0;
					for (int kx = -xradius; kx <= xradius; ++kx)
						for (int ky = -yradius; ky <= yradius; ++ky) {
							int ny = y;
							int nx = x;

							if (nx + kx < 0)
								nx = -kx;
							else if (nx + kx >= maxX)
								nx = maxX - 1 - kx;

							if (ny + ky < 0)
								ny = -ky;
							else if (ny + ky >= maxX)
								ny = maxX - 1 - ky;

							total += src.getSample(nx + kx, ny + ky, ch);
						}

					int newPixelVal = total
							/ ((xradius * 2 + 1) * (yradius * 2 + 1));
					dest.setSample(x, y, ch, newPixelVal);
				}
			}

		return dest;
	}
}